#include "ls_struct_flash.h"
#include "bflb_flash.h"

#define BFLB_FALSH_SIZE     0x400000
#define BFLB_TABLE_ADDRESS  (BFLB_FALSH_SIZE-1024)
#define MAGIC_CODE          0x5AA555AA

typedef int (*p_pt_table_flash_erase)(uint32_t startaddr, uint32_t endaddr);
typedef int (*p_pt_table_flash_write)(uint32_t addr, uint8_t *data, uint32_t len);
typedef int (*p_pt_table_flash_read)(uint32_t addr, uint8_t *data, uint32_t len);

#pragma pack(1) //1024
typedef struct lsSTRUCT_FLASH{
    uint32_t  magic;  
    uint32_t  main[32]; //当前运行程序的分区名字
    uint32_t  ota_status;
    uint32_t  ota_name[32];  //OTA程序的名字

}STRUCT_FLASH;
#pragma pack()

static uint8_t inited = 0;
//ATTR_PSRAM_SECTION
static  STRUCT_FLASH gstStructFlash;

static p_pt_table_flash_erase flash_erase = bflb_flash_erase;
static p_pt_table_flash_write flash_write = bflb_flash_write;
static p_pt_table_flash_read  flash_read = bflb_flash_read;

/// @brief 
void ls_struct_falsh_init()
{
    if(inited == 1) return ;
    flash_read(BFLB_TABLE_ADDRESS,&gstStructFlash,sizeof(STRUCT_FLASH));
    if(gstStructFlash.magic != MAGIC_CODE)
    {
        memset(&gstStructFlash,0,sizeof(STRUCT_FLASH));
        gstStructFlash.magic = MAGIC_CODE;
        flash_erase(BFLB_TABLE_ADDRESS,sizeof(STRUCT_FLASH));
        flash_write(BFLB_TABLE_ADDRESS,&gstStructFlash,sizeof(STRUCT_FLASH));
    }
}


/// @brief 
/// @param name 
void ls_struct_setMainName(const char *name)
{
    ls_struct_falsh_init();

    strcpy(gstStructFlash.main,name);
    flash_erase(BFLB_TABLE_ADDRESS,sizeof(STRUCT_FLASH));
    flash_write(BFLB_TABLE_ADDRESS,&gstStructFlash,sizeof(STRUCT_FLASH));    
}


/// @brief 
/// @param name 
void ls_struct_getMainName(char *name)
{
   ls_struct_falsh_init();
   
   strcpy(name,gstStructFlash.main);  
}



/// @brief 
/// @param name 
void ls_struct_setOTAName(const char *name)
{
   ls_struct_falsh_init();
   gstStructFlash.ota_status = 1; 
   strcpy(gstStructFlash.ota_name,name);
   flash_erase(BFLB_TABLE_ADDRESS,sizeof(STRUCT_FLASH));
   flash_write(BFLB_TABLE_ADDRESS,&gstStructFlash,sizeof(STRUCT_FLASH));
}

/// @brief 
/// @param name 
uint32_t ls_struct_getOTAName(char *name)
{
   ls_struct_falsh_init();
   strcpy(name,gstStructFlash.ota_name);
   return gstStructFlash.ota_status; 
}